package com.ihome.android.market2.asynctask;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ihome.android.EAApp;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.academy.RankingActivity;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.info.AppDetailInfo;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.MyProgressDialog;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 获取应用排行榜信息
 * 
 * @author Emerson
 * 
 */
public class GetAppRankingTask extends AsyncTask<Bundle, Integer, Bundle> {
	private final String					TAG				= GetAppRankingTask.class.getSimpleName();
	private Context							context;
	private MyProgressDialog				progressDialog;
	private int								contentID		= 0;
	private List<TemplateContentInfo>		mSectionContentList;
	//	private final String				RANKLIST_CONTENTCODE	= "0x10003";
	//	private final int					FIRST_RANK				= 0x01;
	//	private final int					SECOND_RANK				= 0x02;
	//	private final int					THIRD_RANK				= 0x03;
	//	private final String				RANK_ALL				= "总";
	//	private final String				RANK_GAME				= "游戏";
	//	private final String				RANK_EDU				= "教育";
	private List<List<TemplateContentInfo>>	mAppListCollect;
	private List<String>					mRankTitleList	= null;
	private List<TemplateContentInfo>		mAppListFirst	= null;
	private List<TemplateContentInfo>		mAppListSecond	= null;
	private List<TemplateContentInfo>		mAppListThird	= null;

	public GetAppRankingTask(Context context) {
		this.context = context;
		mRankTitleList = new ArrayList<String>();
		mRankTitleList.clear();
		mAppListCollect = new ArrayList<List<TemplateContentInfo>>();
		mAppListCollect.clear();
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (!(context instanceof Activity))
			return;
		progressDialog = MyProgressDialog.getDialog(context, context.getString(R.string.user_grabing_data));
		progressDialog.show();
		progressDialog.setCancelable(true);
		progressDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (GetAppRankingTask.this.getStatus().compareTo(AsyncTask.Status.FINISHED) != 0)
					GetAppRankingTask.this.cancel(true);
			}
		});
	}

	@Override
	protected Bundle doInBackground(Bundle... params) {
		Bundle b = params[0];
		int sectionId = b.getInt(HttpKeys.KEY_SECTIONID);
		LogUtil.v(TAG, "sectionId = " + sectionId + ";");

		try {

			String sectionContent = new HttpActions(context).getSectionContent(EAApp.getApp().cacheKey, sectionId);
			LogUtil.d(TAG, "GetAppRankingTask--------->sectionContent = \n" + sectionContent);
			if (!TextUtils.isEmpty(sectionContent)) {
				mSectionContentList = JsonAnalytic.getInstance().anslyseTemplateContent(sectionContent);

				//keep list size <= 3
				int size = mSectionContentList.size() > 3 ? 3 : mSectionContentList.size();
				for (int i = 0; i < size; i++) {
					TemplateContentInfo titleInfo = mSectionContentList.get(i);
					mRankTitleList.add(titleInfo.getName());
					
					String appContent = new HttpActions(context).getSectionContent(EAApp.getApp().cacheKey, titleInfo.getContentId());
					LogUtil.d(TAG, "GetAppRankingTask--------->appContent = \n" + appContent);
					if (!TextUtils.isEmpty(appContent)) {
						//						mAppList = JsonAnalytic.getInstance().anslyseTemplateContent(appContent);
						//						mAppListCollect.add(mAppList);

						if (i == 0) {
							mAppListFirst = JsonAnalytic.getInstance().anslyseTemplateContent(appContent);
							mAppListCollect.add(mAppListFirst);
						}
						if (i == 1) {
							//							LogUtil.d(TAG, "mAppListSecond->size ="+mAppListSecond.size());
							mAppListSecond = JsonAnalytic.getInstance().anslyseTemplateContent(appContent);
							mAppListCollect.add(mAppListSecond);
						}
						if (i == 2) {
							mAppListThird = JsonAnalytic.getInstance().anslyseTemplateContent(appContent);
							mAppListCollect.add(mAppListThird);
						}
					}
				}
			}
			else {
				cancel(true);
			}

		} catch (ITVException e) {
			String[] msg1 = { "", "", "" , "", "operation.sectionContent", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
			e.printStackTrace();
			LogUtil.e(TAG, e.toString());
			b.putInt(HttpKeys.KEY_CODE, e.getStatusCode());
			b.putString(HttpKeys.KEY_DESCRIPTION, e.getMessage());
		}
		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);
		if (progressDialog != null)
			progressDialog.dismiss();

		/** 请求出错处理 */
		if (result.containsKey(HttpKeys.KEY_CODE)) {
			if(ITVException.CODE_LOGINOUT_THREE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGINOUT_ONE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_SESSIONKEY == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGIN_ONE == result.getInt(HttpKeys.KEY_CODE)){
				new DialogFactory(context).showDialog("",result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")",context.getString(R.string.dialog_ok),new onBtnClickListener() {
					
					@Override
					public void btnRightClickListener(View v) {
						// TODO Auto-generated method stub
					}
					
					@Override
					public void btnNeutralClickListener(View v) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void btnLeftClickListener(View v) {
						// TODO Auto-generated method stub
						EAApp.getApp().exitApp(true);
					}
					
					@Override
					public void btnCloseClickListener(View v) {
						// TODO Auto-generated method stub
						
					}
				});
				return;
			}
			new DialogFactory(context).showDialog(result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")");
			return;
		}

		if (RankingActivity.class.isInstance(context) && mAppListCollect.size() != 0) {
			LogUtil.d(TAG, "mAppListCollect.size = " + mAppListCollect.size());
			for (int i = 0; i < mAppListCollect.size(); i++) {
				((RankingActivity) context).fillUpRankTitle(i + 1, mRankTitleList.get(i));
				((RankingActivity) context).fillUpRankinglist(i + 1, mAppListCollect.get(i));				
			}
		}
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		LogUtil.i(TAG, "--> onCancelled");
		if (progressDialog != null)
			progressDialog.dismiss();

	}

}
